package com.qf.air.core.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.air.core.entity.User;
import com.qf.air.core.service.UserService;
import com.qf.air.core.util.R;
import com.qf.air.core.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 维多利加
 * @Date: 2021/3/28 16:41
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     # 请求路径&请求方式
     POST 	http://localhost/user/signin
     # 请求参数
     username = 用户名
     password = 密码
     */
    @PostMapping("/signin")
    public ResultVO signin(String username, String password, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        //1. 校验参数
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            System.out.println("用户名和密码均为必填项，岂能为空！");
            return R.error(222,"用户名和密码均为必填项，岂能为空！");
        }

        //2. 调用service执行登录
        User user = userService.login(username, password);

        //3. 将登录成功的用户信息存储到Session中
//        session.setAttribute("user",user);









        //将登录成功的用户信息存储到redis中



            //将用户信息序列化
            ObjectMapper mapper = new ObjectMapper();
            String value = mapper.writeValueAsString(user);

            //生成uuid
            String key = UUID.randomUUID().toString();

            //存到redis中
            stringRedisTemplate.opsForValue().set(key, value, 1800, TimeUnit.SECONDS);

            //将存储用户信息的key，作为cookie写回到浏览器端
            //创建cookie
            Cookie cookie = new Cookie("userCookie", key);
            //设置路径
//            String contextPath = request.getContextPath();
            cookie.setPath("/");
            //设置有效期
            cookie.setMaxAge(60*60*24);
            cookie.setHttpOnly(true);
            //把cookie放入response中
            response.addCookie(cookie);

        //4. R.ok();
        return R.ok();
    }

}
